<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use app\common\model\UserMain;
use app\common\model\UserSiteAccess;
use think\facade\Config;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;

class User extends Base
{
    public function index()
    {
        $map = $page_query = [];
        if ($start_uid = Request::param('start_uid', '')) {
            $map[]                   = ['uid', '>=', $start_uid];
            $page_query['start_uid'] = $start_uid;
        }
        if ($end_uid = Request::param('end_uid', '')) {
            $map[]                 = ['uid', '<=', $end_uid];
            $page_query['end_uid'] = $end_uid;
        }
        if ($start_balance = Request::param('start_balance', '')) {
            $map[]                       = ['balance', '>=', $start_balance];
            $page_query['start_balance'] = $start_balance;
        }
        if ($end_balance = Request::param('end_balance', '')) {
            $map[]                     = ['balance', '<=', $end_balance];
            $page_query['end_balance'] = $end_balance;
        }
        if ($start_register_time = Request::param('start_register_time', '')) {
            $map[]                             = ['register_time', '>=', strtotime($start_register_time)];
            $page_query['start_register_time'] = $start_register_time;
        }
        if ($end_register_time = Request::param('end_register_time', '')) {
            $map[]                           = ['register_time', '<=', strtotime($end_register_time)];
            $page_query['end_register_time'] = $end_register_time;
        }
        if ($start_parse_times = Request::param('start_parse_times', '')) {
            $map[]                           = ['parse_times', '>=', $start_parse_times];
            $page_query['start_parse_times'] = $start_parse_times;
        }
        if ($end_parse_times = Request::param('end_parse_times', '')) {
            $map[]                         = ['parse_times', '<=', $end_parse_times];
            $page_query['end_parse_times'] = $end_parse_times;
        }
        if ($start_parse_max_time = Request::param('start_parse_max_time', '')) {
            $map[]                              = ['parse_max_times', '>=', $start_parse_max_time];
            $page_query['start_parse_max_time'] = $start_parse_max_time;
        }
        if ($end_parse_max_times = Request::param('end_parse_max_times', '')) {
            $map[]                             = ['parse_max_times', '<=', $end_parse_max_times];
            $page_query['end_parse_max_times'] = $end_parse_max_times;
        }
        if ($username = Request::param('username', '')) {
            $map[]                  = ['username', 'like', '%' . $username . '%'];
            $page_query['username'] = $username;
        }
        if ($qq = Request::param('qq', '')) {
            $map[]            = ['qq', 'like', '%' . $qq . '%'];
            $page_query['qq'] = $qq;
        }
        if ($weixin = Request::param('weixin', '')) {
            $map[]                = ['weixin', 'like', '%' . $weixin . '%'];
            $page_query['weixin'] = $weixin;
        }
        if ($email = Request::param('email', '')) {
            $map[]               = ['email', 'like', '%' . $email . '%'];
            $page_query['email'] = $email;
        }
        if ($mobile = Request::param('mobile', '')) {
            $map[]                = ['mobile', 'like', '%' . $mobile . '%'];
            $page_query['mobile'] = $mobile;
        }
        if ($type = Request::param('type', '')) {
            $map[]              = ['type', '=', $type];
            $page_query['type'] = $type;
        }
        $count = [
            'all'    => UserMain::count('uid'),
            'search' => UserMain::where($map)->count('uid'),
        ];
        $orderBy = in_array(Request::param('orderBy'), ['uid']) ? Request::param('orderBy') : 'uid';
        $order   = in_array(Request::param('order'), ['asc', 'desc']) ? Request::param('order') : 'desc';

        $user_list = UserMain::where($map)->order($orderBy, $order)->paginate([
            'list_rows' => 15,
            'query'     => $page_query,
        ]);
		
        return View::assign([
            'user_list' => $user_list,
            'count'     => $count,
            'is_search' => empty($map) ? false : true,
            'page'      => $user_list->render(),
        ])->fetch();	
    }

    public function export_user()
    {
        if (Request::isPost()) {
            $map = $web_site_list = [];
            foreach (WebSite::select() as $site) {
                $web_site_list[$site['site_id']] = $site;
            }
            if ($start_uid = Request::post('start_uid', '')) {
                $map[] = ['uid', '>=', $start_uid];
            }
            if ($end_uid = Request::post('end_uid', '')) {
                $map[] = ['uid', '<=', $end_uid];
            }
            if ($start_balance = Request::post('start_balance', '')) {
                $map[] = ['balance', '>=', $start_balance];
            }
            if ($end_balance = Request::post('end_balance', '')) {
                $map[] = ['balance', '<=', $end_balance];
            }
            if ($start_register_time = Request::post('start_register_time', '')) {
                $map[] = ['register_time', '>=', strtotime($start_register_time)];
            }
            if ($end_register_time = Request::post('end_register_time', '')) {
                $map[] = ['register_time', '<=', strtotime($end_register_time)];
            }
            if ($start_parse_times = Request::post('start_parse_times', '')) {
                $map[] = ['parse_times', '>=', $start_parse_times];
            }
            if ($end_parse_times = Request::post('end_parse_times', '')) {
                $map[] = ['parse_times', '<=', $end_parse_times];
            }
            if ($start_parse_max_time = Request::post('start_parse_max_time', '')) {
                $map[] = ['parse_max_times', '>=', $start_parse_max_time];
            }
            if ($end_parse_max_times = Request::post('end_parse_max_times', '')) {
                $map[] = ['parse_max_times', '<=', $end_parse_max_times];
            }
            if ($username = Request::post('username', '')) {
                $map[] = ['username', 'like', '%' . $username . '%'];
            }
            if ($qq = Request::post('qq', '')) {
                $map[] = ['qq', 'like', '%' . $qq . '%'];
            }
            if ($weixin = Request::post('weixin', '')) {
                $map[] = ['weixin', 'like', '%' . $weixin . '%'];
            }
            if ($email = Request::post('email', '')) {
                $map[] = ['email', 'like', '%' . $email . '%'];
            }
            if ($mobile = Request::post('mobile', '')) {
                $map[] = ['mobile', 'like', '%' . $mobile . '%'];
            }
            if ($type = Request::post('type', '')) {
                $map[] = ['type', '=', $type];
            }
            $expCellName = [];
            foreach (Request::post('fields/a', []) as $field => $name) {
                $expCellName[] = [$field, $name];
            }
            $user_list   = UserMain::with(['site_access'])->where($map)->select();
            $cellNum     = count($expCellName);
            $dataNum     = count($user_list);
            $objPHPExcel = new \PHPExcel();
            $cellName    = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'];
            for ($i = 0; $i < count($expCellName); $i++) {
                $objPHPExcel->getActiveSheet()->getColumnDimension($cellName[$i])->setWidth(15);
            }
            $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');
            $objPHPExcel->getActiveSheet()->setCellValue('A1', '会员数据')->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            for ($i = 0; $i < $cellNum; $i++) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
            }
            for ($i = 0; $i < $dataNum; $i++) {
                for ($j = 0; $j < $cellNum; $j++) {
                    if (in_array($expCellName[$j][0], ['status', 'type'])) {
                        $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), $user_list[$i][$expCellName[$j][0] . '_text']);
                    } else if ($expCellName[$j][0] == 'parse_max_times') {
                        $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), $user_list[$i][$expCellName[$j][0]] ?: '无限制');
                    } else if ($expCellName[$j][0] == 'site_access') {
                        $data = [];
                        foreach ($user_list[$i]['site_access'] as $site_access) {
                            if (empty($web_site_list[$site_access['site_id']]) || empty($site_access) || $site_access['day_times'] < 0 || $site_access['week_times'] < 0 || $site_access['month_times'] < 0 || $site_access['year_times'] < 0 || $site_access['max_times'] < 0) {
                                continue;
                            }
                            $data[] = $web_site_list[$site_access['site_id']]['title'] . '：' . implode('/', [$site_access['day_times'], $site_access['week_times'], $site_access['month_times'], $site_access['year_times'], $site_access['max_times']]);
                        }
                        $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), implode(PHP_EOL, $data));
                    } else {
                        $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), $user_list[$i][$expCellName[$j][0]]);
                    }
                }
            }
            $filename = '会员数据';
            ob_end_clean();
            header('pragma:public');
            header('Content-type:application/octet-stream;charset=utf-8;name="' . $filename . '.xls"');
            header("Content-Disposition:attachment;filename=" . $filename . ".xls");
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
            exit;
        }
        return View::fetch();
    }

    public function search_user()
    {
        if (Request::isPost()) {
            $param = [];
            if ('' !== $start_uid = Request::post('start_uid', '')) {
                $param['start_uid'] = $start_uid;
            }
            if ('' !== $end_uid = Request::post('end_uid', '')) {
                $param['end_uid'] = $end_uid;
            }
            if ('' !== $start_balance = Request::post('start_balance', '')) {
                $param['start_balance'] = $start_balance;
            }
            if ('' !== $end_balance = Request::post('end_balance', '')) {
                $param['end_balance'] = $end_balance;
            }
            if ('' !== $start_register_time = Request::post('start_register_time', '')) {
                $param['start_register_time'] = $start_register_time;
            }
            if ('' !== $end_register_time = Request::post('end_register_time', '')) {
                $param['end_register_time'] = $end_register_time;
            }
            if ('' !== $start_parse_times = Request::post('start_parse_times', '')) {
                $param['start_parse_times'] = $start_parse_times;
            }
            if ('' !== $end_parse_times = Request::post('end_parse_times', '')) {
                $param['end_parse_times'] = $end_parse_times;
            }
            if ('' !== $start_parse_max_time = Request::post('start_parse_max_time', '')) {
                $param['start_parse_max_time'] = $start_parse_max_time;
            }
            if ('' !== $end_parse_max_times = Request::post('end_parse_max_times', '')) {
                $param['end_parse_max_times'] = $end_parse_max_times;
            }
            if ('' !== $username = Request::post('username', '')) {
                $param['username'] = $username;
            }
            if ('' !== $qq = Request::post('qq', '')) {
                $param['qq'] = $qq;
            }
            if ('' !== $weixin = Request::post('weixin', '')) {
                $param['weixin'] = $weixin;
            }
            if ('' !== $email = Request::post('email', '')) {
                $param['email'] = $email;
            }
            if ('' !== $mobile = Request::post('mobile', '')) {
                $param['mobile'] = $mobile;
            }
            if ('' !== $type = Request::post('type', '')) {
                $param['type'] = $type;
            }
            return redirect('admin/user/index', $param);
        }
        return View::fetch();
    }

    public function add_user()
    {
        if (Request::isAjax() && Request::isPost()) {
            $post     = Request::post();
            $validate = Validate::rule([
                'username' => 'require|max:30|unique:user_main',
                'password' => 'require',
                'mobile'   => 'mobile|unique:user_main',
                'email'    => 'email|unique:user_main',
            ])->message([
                'username.require' => '用户名必填',
                'username.max'     => '用户名最大长度30字符',
                'username.unique'  => '用户名已存在',
                'password.require' => '登录密码必填',
                'mobile.unique'    => '手机号已存在',
                'email.email'      => '邮箱输入错误',
                'email.unique'     => '邮箱已存在',
            ]);

            if (!$validate->check($post)) {
                return show_error($validate->getError());
            }
            $post['password_see'] = $post['password'];
            $user                 = UserMain::create($post);

            if (false !== $user->getError()) {
                return show_error($user->getError());
            }

            return show_success('用户创建成功', 'admin/user/index');
        }
        return View::fetch('edit_user');
    }

    public function edit_user($uid = 0)
    {
        $user = UserMain::with(['site_access'])->where('uid', '=', $uid)->find();
        if (empty($user)) {
            return show_error('指定数据不存在');
        }


        if (Request::isAjax() && Request::isPost()) {
            $post     = Request::post();
            $validate = Validate::rule([
                'username' => 'require|max:30|unique:user_main,username,' . $user->uid,
                'mobile'   => 'unique:user_main,mobile,' . $user->uid,
                'email'    => 'email|unique:user_main,email,' . $user->uid,
            ])->message([
                'username.require' => '用户名必填',
                'username.max'     => '用户名最大长度30字符',
                'username.unique'  => '用户名已存在',
                'mobile.unique'    => '手机号已存在',
                'email.email'      => '邮箱输入错误',
                'email.unique'     => '邮箱已存在',
            ]);

            if (!$validate->check($post)) {
                return show_error($validate->getError());
            }
            $password = trim($post['password']);
            if ($password == '') {
                unset($post['password']);
                unset($post['password_see']);
            } else {
                $post['password_see'] = $post['password'];
            }
            $user->save($post);
            if (false !== $user->getError()) {
                return show_error($user->getError());
            }

            $old_access = [];
            foreach (UserSiteAccess::where('uid', '=', $user->uid)->select() as $access) {
                $old_access[$access['site_id']] = $access;
            }

            return show_success('用户信息保存成功', 'admin/user/index');
        }

        return View::assign([
            'user'          => $user,
            'site_access'   => [],
        ])->fetch('edit_user');
    }

    public function batch_add()
    {
        $web_site_list = [];
        foreach (WebSite::order('site_id', 'desc')->select() as $web_site) {
            $web_site_list[$web_site['site_id']] = $web_site;
        }
        if (Request::isAjax() && Request::isPost()) {

            $post     = Request::post();
            $validate = Validate::rule([
                'username' => 'require',
                'password' => 'require',
                'numbers'  => 'require|integer|>:0|<=:200',
            ])->message([
                'username.require' => '用户名必填',
                'username.unique'  => '用户名已存在',
                'password.require' => '密码必填',
                'numbers'          => '生成数量只能是1-200之间的整数',
            ]);

            if (!$validate->check($post)) {
                return show_error($validate->getError());
            }

            $username = $password = [];
            for ($i = 0; $i < $post['numbers']; $i++) {
                $username[$i] = replace_random_str($post['username']);
                $password[$i] = replace_random_str($post['password']);
            }
            foreach (UserMain::where('username', 'in', $username)->field('uid,username')->select() as $old) {
                $k = array_search($old['username'], $username);
                unset($username[$k]);
            }
            $new_count = 0;
            foreach ($username as $k => $name) {
                $user = UserMain::create([
                    'username'        => $name,
                    'password'        => strtolower($password[$k]),
                    'password_see'    => strtolower($password[$k]),
                    'balance'         => $post['balance'],
                    'parse_max_times' => (int) $post['parse_max_times'],
                    'type'            => $post['type'],
                    'discount'        => $post['discount'],
                    'status'          => $post['status'],
                ]);
                if (false !== $user->getError()) {
                    continue;
                }
                $site_access = [];
                foreach ($post['day_times'] as $site_id => $day_times) {
                    if (empty($web_site_list[$site_id])) {
                        continue;
                    }
                    $site_access[] = [
                        'uid'         => $user->uid,
                        'site_id'     => (int) $site_id,
                        'parse_times' => 0,
                        'day_times'   => (int) $day_times,
                        'week_times'  => (int) $post['week_times'][$site_id],
                        'month_times' => (int) $post['month_times'][$site_id],
                        'year_times'  => (int) $post['year_times'][$site_id],
                        'max_times'   => (int) $post['max_times'][$site_id],
                        'out_time'    => $post['out_time'][$site_id],
                    ];
                }
                (new UserSiteAccess)->saveAll($site_access);
                $new_count++;
            }
            return show_success('本次成功生成' . $new_count . '个账号！', 'admin/user/index');
        }
        return View::assign([
            'web_site_list' => $web_site_list,
        ])->fetch();
    }

    public function delete_user($uid = 0)
    {
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $data = UserMain::where('uid', '=', $uid)->find();
        if (empty($data)) {
            return show_error('指定数据不存在');
        }
        if (in_array($data['uid'], Config::get('app.founder'))) {
            return show_error('请先删除其超级管理员身份');
        }
        $data->delete();
        return show_success('数据删除成功', 'admin/user/index');
    }
}
